<script setup lang="tsx">
import { useRemoteStore } from '@/stores/remote'
import { storeToRefs } from 'pinia'
import { onMounted, onUnmounted } from 'vue'
import './peer-pupet'

const remoteStore = useRemoteStore()
const { setRemoteCode, setLocalCode, setControlText } = remoteStore
// 获取远程控制码
const { remoteCode } = storeToRefs(useRemoteStore())
// 获取本地控制码
const { localCode } = storeToRefs(useRemoteStore())
// 控制状态文案
const { controlText } = storeToRefs(useRemoteStore())

const login = async () => {
  // 登录
  const code = await window.ipcRenderer.invoke('login')
  setLocalCode(code)
}

const handleControlStateChange = (name: string, type: number) => {
  console.log('🚀 ~ remote.vue:23 ~ handleControlStateChange ~ name:', name, type)

  let text = ''
  if (type === 1) {
    // 控制别人
    text = `正在远程控制${name}`
    window.control.emit('get-offer')
    // window.ipcRenderer.send('get-offer')
  } else if (type === 2) {
    // 被控制
    text = `被${name}远程控制`
  }
  setControlText(text)
}
const startControl = async (code: string) => {
  // 开始控制,控制该控制码对应的用户
  await window.ipcRenderer.send('control', code)
}

onMounted(() => {
  login()
  // 监听控制状态是否发生了改变
  window.ipcRenderer.on('control-state-change', handleControlStateChange)
})

onUnmounted(() => {
  window.ipcRenderer.removeListener('control-state-change', handleControlStateChange)
})

// JSX 渲染函数
const renderCounter = () => {
  return (
    <div class="counter">
      {controlText.value === '' ? (
        // jsx 表达式必须有一个父元素
        <>
          <div>你的控制码：{localCode.value}</div>
          <input
            v-bind:value={remoteCode.value}
            onChange={(e) => setRemoteCode(e?.target?.value || '')}
            placeholder="请输入对方控制码"
          />
          <button onClick={() => startControl(remoteCode.value)}>确认</button>
        </>
      ) : (
        // 有连接状态，直接显示连接状态
        <div> {controlText.value}</div>
      )}
    </div>
  )
}
</script>

<template>
  <!-- 在模板中调用 JSX 渲染函数 -->
  <renderCounter />
</template>
